AC_DEFUN([AC_ONIGURUMA],
[
AC_ARG_WITH([oniguruma],
            AS_HELP_STRING([--with-oniguruma=prefix],
                           [specify oniguruma installed prefix (default is /usr/local)]),
            [ac_oniguruma_prefix="$withval"],
            [ac_oniguruma_prefix="/usr/local"])

AC_ARG_VAR([ONIGURUMA_CFLAGS],
           [C compiler flags for oniguruma
            (default is -I<oniguruma_prefix>/include)])
AC_ARG_VAR([ONIGURUMA_LIBS],
           [linker flags for oniguruma
            (default is -L<oniguruma_prefix>/lib -lonig)])

if test "$ONIGURUMA_CFLAGS" = ""; then
  ONIGURUMA_CFLAGS="-I$ac_oniguruma_prefix/include"
fi
if test "$ONIGURUMA_LIBS" = ""; then
  ONIGURUMA_LIBS="-L$ac_oniguruma_prefix/lib -lonig"
fi

CPPFLAGS_SAVED="$CPPFLAGS"
CPPFLAGS="$CPPFLAGS $ONIGURUMA_CFLAGS"
export CPPFLAGS

LDFLAGS_SAVED="$LDFLAGS"
LDFLAGS="$LDFLAGS $ONIGURUMA_LIBS"
export LDFLAGS

_tmp="$ONIGURUMA_LIBS"
while test 1; do
  if test "${_tmp##-L*}" = ""; then
    _tmp_dir=`echo $_tmp | sed -e 's/^-L *\(@<:@^ @:>@*\).*$/\1/'`
    LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$_tmp_dir"
  fi
  if test "$_tmp" = "${_tmp#* }"; then
    break
  fi
  _tmp="${_tmp#* }"
done
export LD_LIBRARY_PATH

AC_LANG_PUSH([C])
AC_CHECK_HEADER([oniguruma.h], , [AC_MSG_ERROR([oniguruma.h is required])])
if test "$1" != ""; then
  AC_MSG_CHECKING([for oniguruma version >= $1])
  req_major=`echo $1 | sed -e 's/\./ /g' | awk '{print @S|@1;}'`
  req_minor=`echo $1 | sed -e 's/\./ /g' | awk '{print @S|@2;}'`
  req_teeny=`echo $1 | sed -e 's/\./ /g' | awk '{print @S|@3;}'`
  CPPFLAGS="$CPPFLAGS -DONIGURUMA_REQ_MAJOR=$req_major -DONIGURUMA_REQ_MINOR=$req_minor -DONIGURUMA_REQ_TEENY=$req_teeny"
  export CPPFLAGS
  AC_COMPILE_IFELSE(AC_LANG_PROGRAM([[
@%:@include <stdlib.h>
@%:@include <oniguruma.h>
]], [[
@%:@if (ONIGURUMA_REQ_MAJOR > ONIGURUMA_VERSION_MAJOR || \
        (ONIGURUMA_REQ_MAJOR == ONIGURUMA_VERSION_MAJOR && ONIGURUMA_REQ_MINOR > ONIGURUMA_VERSION_MINOR) || \
        (ONIGURUMA_REQ_MAJOR == ONIGURUMA_VERSION_MAJOR && ONIGURUMA_REQ_MINOR == ONIGURUMA_VERSION_MINOR && ONIGURUMA_REQ_TEENY > ONIGURUMA_VERSION_TEENY))
@%:@ error
@%:@endif
]]),
                [AC_MSG_RESULT([yes])],
                [AC_MSG_RESULT([no])
                 AC_MSG_ERROR([oniguruma version mismatch!])])
fi
AC_LANG_POP([C])

CPPFLAGS="$CPPFLAGS_SAVED"
LDFLAGS="$LDFLAGS_SAVED"

AC_SUBST(ONIGURUMA_CFLAGS)
AC_SUBST(ONIGURUMA_LIBS)
])